// 云函数入口文件
const cloud = require('wx-server-sdk');
// 引入request-promise用于网络请求
const rp = require('request-promise');

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const openId = event.userInfo.openId;
  // 根据openId与时间戳生成密钥
  let key = getKey(openId);

  let obj = {
    openId,
    key,
    title: event.title,
    hour: event.hour,
    minute: event.minute
  };
  if(event.dayOfWeek){
    obj['dayOfWeek'] = event.dayOfWeek;
  }else if(event.year&&event.month&&event.dayOfMonth){
    obj['year'] = event.year;
    obj['month'] = event.month;
    obj['dayOfMonth'] = event.dayOfMonth;
  }

  // 请求配置
  let options = {
    method: 'GET',
    url: 'xxx.xyz/newPlan',
    qs: obj,
    json: true
  }

  return await rp(options)
    .then(res=>res)
    .catch(console.error);
}

// 根据openId与时间戳生成密钥
function getKey(openId){
  let time = new Date().getTime().toString();
  let key = openId.split('').reverse().join('').substr(0,time.length).split('').map((a,i)=>String.fromCharCode(a.charCodeAt()+ +time[i])).join('');
  return key;
}